package de.suur.jarmi.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import de.suur.jarmi.common.JarmiUtil;
import de.suur.jarmi.common.Response;

/**
 * @author Simon Joecks
 */
public class JarmiHttpServer {

	private class HttpRequestHandler implements HttpHandler {

		public void handle(HttpExchange exchange) throws IOException {
			String method = exchange.getRequestMethod();
			Headers headers = exchange.getRequestHeaders();
			log.trace("Request method: {}", method);
			log.trace("Request headers: {}", headers.size());
			for (String header : headers.keySet()) {
				String string = " " + header + " = ";
				List<String> values = headers.get(header);
				for (String value : values) {
					string += value + ", ";
				}
				log.trace(string);
			}

			Response response = requestHandler
					.handle(exchange.getRequestBody());
			byte[] responseData = requestHandler.serialize(response);
			responseData = requestHandler.compress(responseData);
			exchange.sendResponseHeaders(200, responseData.length
					+ JarmiUtil.JARMI_BYTES.length);
			requestHandler.writeResponse(exchange.getResponseBody(),
					responseData);
		}

	}

	private static final transient Logger log = LoggerFactory
			.getLogger(JarmiHttpServer.class);

	private final String path;
	private final int port;
	private RequestHandler requestHandler;

	private HttpServer server;

	public JarmiHttpServer(int port, String path) throws IOException {
		this.port = port;
		this.path = path;
		initServer();
	}

	public RequestHandler getRequestHandler() {
		return requestHandler;
	}

	private void initServer() throws IOException {
		server = HttpServer.create(new InetSocketAddress(port), 0);
		server.createContext(path, new HttpRequestHandler());
		server.setExecutor(null);
	}

	public void setRequestHandler(RequestHandler requestHandler) {
		this.requestHandler = requestHandler;
	}

	public void start() {
		server.start();
	}

	public void stop() {
		server.stop(0);
	}

}
